package com.mk.episodecalendar.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mk.episodecalendar.EpisodeCollection;
import com.mk.episodecalendar.Global;
import com.mk.episodecalendar.R;
import com.mk.episodecalendar.User;

public class EpisodeFeed extends Activity {

	private String listIsLoadedFor = "";
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.episode_feed_list);
		
		Global.AutoLoginUser();
		
		Init();
	}
	
	private void Init()
	{
		if(!Global.ApplicationPrecferences.getAutoLogin() || !isValidUser(Global.CurrentUser) )
		{
			Intent myIntent = new Intent(this, Login.class);
	        startActivityForResult(myIntent, 0);
		}
		else
		{
			Load();
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(isValidUser(Global.CurrentUser))
			Load();
		else
			finish();
	}

	private void Load()
	{
		if(!listIsLoadedFor.equals(Global.CurrentUser.getUserName()))
		{
			ArrayList<EpisodeCollection> episodes = Global.EpisodeRepository.GetEpisodes(Global.CurrentUser);
			
			LinearLayout itemsContainer = (LinearLayout)findViewById(R.id.items_container);
			if(episodes.size() > 0)
			{
				TextView emptyTextView = (TextView)findViewById(R.id.empty_list);
				emptyTextView.setVisibility(View.GONE);
			}
			
			for(int i = 0; i < episodes.size(); i++)
			{
				itemsContainer.addView(Global.LayoutObjectFactory.createEpisodeCollectionItem(this, episodes.get(i)));
			}
			
			setTitle(getResources().getString(R.string.app_name) + " - " + Global.CurrentUser.getUserName());
			
			listIsLoadedFor = Global.CurrentUser.getUserName();
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
		MenuItem menuItemLogout = menu.add("Logout");
		menuItemLogout.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Global.signOutCurrentUser();
				listIsLoadedFor = "";
				Init();
				return true;
			}
		});
		
		return super.onCreateOptionsMenu(menu);
    }
	
	private Boolean isValidUser(User user)
	{
		return user != null && user.getIsAuthenticated();
	}
	
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		
		if(isFinishing() && Global.CurrentUser != null)
		{
			Global.CurrentUser.setIsAuthenticated(false);
		}
	}
}
